package org.cancer.hadesdata.controller;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

import java.util.List;

import org.cancer.hadesdata.model.FileType;
import org.cancer.hadesdata.resource.FileTypeResource;
import org.cancer.hadesdata.resource.FileTypeResourceAssembler;
import org.cancer.hadesdata.service.FileService;
import org.cancer.hadesdata.syno.SynoConfig;
import org.cancer.hadesdata.syno.SynoManager.ImageSize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.ExposesResourceFor;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@ExposesResourceFor(FileType.class)
@ResponseBody
@RequestMapping(value = "/file", produces = APPLICATION_JSON_VALUE)
public class FileController {

	@Autowired
	private FileService fileSourceService;

	@Autowired
	private SynoConfig synoConfig;

	@RequestMapping(value = "/findComposites")
	public List<FileTypeResource> findComposites(@RequestParam(required = false) String parentId,
			@RequestParam(defaultValue = "0", required = false) int deep) {
		if (parentId != null && parentId.equals("0"))
			parentId = null;
		return new FileTypeResourceAssembler().toResources(fileSourceService.findComposites(parentId, deep));
	}

	@RequestMapping(value = "/{id}")
	public FileTypeResource fileInfo(@PathVariable String id) {
		if (id == "0")
			id = null;
		return new FileTypeResourceAssembler().toResource(fileSourceService.findById(id));
	}

	@RequestMapping(value = "/findByUrl")
	public FileTypeResource findByUrl(@RequestParam(required = true) String url) {
		return new FileTypeResourceAssembler().toResource(fileSourceService.findByUrl(url));
	}

	@RequestMapping(value = "/imgae")
	public HadesUri image(@RequestParam(required = true) String id, @RequestParam(required = false) String size) {
		return new HadesUri(fileSourceService.image(id, ImageSize.valueOf(size)));
	}

	@RequestMapping(value = "/open")
	public HadesUri open(@RequestParam(required = true) String id) {
		return new HadesUri(fileSourceService.open(id));
	}

	@RequestMapping(value = "/download")
	public HadesUri download(@RequestParam(required = true) String id) {
		return new HadesUri(fileSourceService.download(id));
	}

	@RequestMapping(value = "/getServerConfig")
	public SynoConfig getServerConfig() {
		return synoConfig;
	}
}

class HadesUri {
	private String uri;

	HadesUri(String uri) {
		this.uri = uri;
	}

	public String getUri() {
		return uri;
	}

	public void setUri(String uri) {
		this.uri = uri;
	}

	public String toString() {
		return this.uri;
	}
}
